<!--  -->
<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图  -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolesList"
                style="width: 100%"
                :border="true"
                stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bd-bottom',i1==0 ? 'bd-top':'','vcenter']"
                    v-for="(item1,i1) in scope.row.children"
                    :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="6">
                <el-tag closable
                        @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="18">
                <!-- 渲染二级权限 -->
                <el-row v-for="(item2,i2) in item1.children"
                        :class="[i2===0?'':'bd-top','vcenter']"
                        :key="item2.id">
                  <el-col :span="6">
                    <el-tag closable
                            @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag v-for="(item3,i3) in item2.children"
                            :key="item3.key"
                            type="warning"
                            closable
                            @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
            {{scope.row}}
            </pre> -->
          </template>
        </el-table-column>

        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName"
                         label="角色名称"
                         width="180">
        </el-table-column>
        <el-table-column prop="roleDesc"
                         label="角色描述"
                         width="180">
        </el-table-column>
        <el-table-column prop="address"
                         label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"></el-button>
            <!-- 删除 -->
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"></el-button>
            <!-- 分配角色 -->
            <el-tooltip class="item"
                        effect="dark"
                        content="分配角色"
                        placement="top"
                        :enterable="false">
              <el-button type="warning"
                         icon="el-icon-setting"
                         size="mini"
                         @click="showSetRightDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限"
               :visible.sync="setRightDialogVisible"
               width="30%"
               @close="setRightDialogClosed">
      <!-- 树形控件 -->
      <el-tree :data="rightsList"
               :props="TreeProps"
               show-checkbox
               node-key="id"
               default-expand-all
               ref="treeRef"
               :default-checked-keys="defKeys"></el-tree>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { reqGetRoles, reqDeleteRight, reqGetRights, reqAllotRight } from '@/api/index'
export default {
  data () {
    return {
      // 角色列表
      rolesList: [],
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件需要数据
      TreeProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件三级分类默认选中
      defKeys: [],
      roleId: ''
    }
  },
  methods: {
    // 1.获取所有列表数据
    async getRolesList () {
      const { data: res } = await reqGetRoles()
      if (res.meta.status != 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 2.通过id移除权限事件
    async removeRightById (role, rightId) {
      // 2.1 弹框提示是否要删除
      const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })

      if (res !== 'confirm') {
        return this.$message.error('取消删除权限事件')
      }
      // 2.2删除角色下指定功能
      const { data: result } = await reqDeleteRight(role.id, rightId)
      console.log(result)
      if (result.meta.status !== 200) {
        return this.$message.error('删除权限事件失败')
      }
      // 全局刷新数据
      // this.getRolesList()
      // 局部刷新数据
      role.children = result.data
    },
    // 3.展示分配权限对话框
    async showSetRightDialog (role) {
      this.roleId = role.id
      // 3.1 获取所有权限的数据
      const { data: res } = await reqGetRights('tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      this.rightsList = res.data
      // 获取三级节点的ID
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 4.通过递归的形式，获取角色下所有的三级权限的ID,并保存到defKeys中
    getLeafKeys (node, arr) {
      // 如果当前节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      // 不是三级节点,调用递归
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 5.监听关闭权限对话框的关闭事件
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 6.点击为角色分配权限
    async allotRight () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const rids = keys.join(',')
      const { data: res } = await reqAllotRight(this.roleId, rids)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    }

  },
  // 生命周期 - 创建完成（访问当前this实例）
  created () {

  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted () {
    this.getRolesList()
  }
}
</script>
<style lang="less" scoped>
.el-card {
  margin-top: 20px;
}

.el-table {
  margin-top: 20px;
}

.el-tag {
  margin: 8px;
}

.bd-bottom {
  border-bottom: 1px solid #ccc;
}

.bd-top {
  border-top: 1px solid #ccc;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
